//
//  SharePhotoController.m
//  ox
//
//  Created by 喻杰 on 2016/10/30.
//  Copyright © 2016年 fengge. All rights reserved.
//

#import "SharePhotoController.h"


#define sharePhotoCell @"sharePhotoCell"
#define sharePhotoContentPlaceHolder @"这一刻的想法..."
#define insert_record @"insert into ox_record(content,recorder,record_time,image_url,img_width,img_height,lat,lon,poi_name,address) values(?,?,?,?,?,?,?,?,?,?)"


@interface SharePhotoController()
@end

@implementation SharePhotoController

@synthesize txtContent,image,recorder,model,table,imageView,dbQueue;

- (void)viewDidLoad {
    [super viewDidLoad];
    //导航栏
    UIBarButtonItem* left =[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(navItemAction:)];
    left.tag = 1;
    self.navigationItem.leftBarButtonItem =left;
    
    UIBarButtonItem* right =[[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(navItemAction:)];
    self.navigationItem.rightBarButtonItem =right;
    right.tag = 2;
    
    //
    //    recorder.dataSource = self;
    //    recorder.delegate = self;
    //    [recorder mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(self.view).offset(80);
    //        make.left.mas_equalTo(self.view).offset(10);
    //        make.right.mas_equalTo(10);
    //        make.height.mas_equalTo(80);
    //
    //    }];
    
    //    //输入框
    //    [txtContent mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(recorder).offset(90);
    //        make.left.mas_equalTo(self.view).offset(10);
    //        make.right.mas_equalTo(self.view).offset(-10);
    //        make.height.mas_equalTo(80);
    //
    //    }];
    
    //
    //    //图片
    //    UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
    //    [self.view addSubview:imageView];
    //    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.mas_equalTo(txtContent).offset(90);
    //        make.left.mas_equalTo(self.view).offset(10);
    //        make.size.mas_equalTo(CGSizeMake(100, 100));
    //    }];
    //
    
    model =[[OxRecordModel alloc] init];
    [model setRecorder:@"粑粑"];
    [model setLat:0];
    [model setLon:0];
    [model setPoiName:@""];
    [model setAddress:@""];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    table.dataSource = self;
    table.delegate = self;
    [table registerClass:MyTableCell.class forCellReuseIdentifier:sharePhotoCell];
    
    [self.view addSubview:table];
    
    
    //    [table mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.edges.mas_equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    //    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)navItemAction:(UIBarButtonItem *)sender{
    if(sender.tag == 1){
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        DBHelper* helper =  [[DBHelper alloc]init];
        [model setImageWidth:150];
        [model setImageHeight:150];
        [model setContent:txtContent.text];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
        DDLogInfo(@"%@", strDate);
        [model setRecordTime:strDate];
        NSFileManager* manager = [NSFileManager defaultManager];
        NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/images"];
        int i =  [[NSDate date] timeIntervalSince1970];
        NSString* fileName =  [[[NSString alloc]initWithFormat:@"%d",i] stringByAppendingString:@".jpg"];
        BOOL isDic = YES;
        if(![manager fileExistsAtPath:path isDirectory:&isDic]){
            [manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        }
        path = [path stringByAppendingString:@"/" ];
        path = [path stringByAppendingString: fileName ];
        if([manager createFileAtPath:path contents:UIImagePNGRepresentation(image) attributes:nil]){
            [model setImageUrl:path];
            [model setImageWidth:image.size.width];
            [model setImageHeight:image.size.height];
            if(!dbQueue){
                DDLogInfo(@"%@",@"%创建队列");
                dbQueue = dispatch_queue_create(recordQueue, DISPATCH_QUEUE_SERIAL);
            }
            dispatch_async(dbQueue, ^{
                [helper excuteBy:insert_record values:@[model.content,model.recorder,model.recordTime,model.imageUrl,@(model.imageWidth),@(model.imageHeight),@(model.lat),@(model.lon),model.poiName,model.address]];
            });
            [txtContent resignFirstResponder];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return 3;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (row == 0) {
        return @"粑粑";
    }else if(row == 1){
        return @"麻麻";
    }else{
        return @"牛牛";
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger) component{
    if(row == 0 && component ==0){
        [model setRecorder:@"粑粑"];
    }else if(row==1 &&component ==0){
        [model setRecorder:@"麻麻"];
    }else{
        [model setRecorder:@"牛牛"];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger numberOfRows;
    switch (section) {
        case 0:
            numberOfRows = 2;
            break;
        case 1:
            numberOfRows = 1;
            break;
        default:
            numberOfRows = 1;
            break;
    }
    return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyTableCell* cell = [tableView dequeueReusableCellWithIdentifier:sharePhotoCell];
    if(nil==cell){
        cell = [[MyTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sharePhotoCell];
    }
    if (indexPath.section==0) {
        if(indexPath.row==0){
            cell.textLabel.text = @"谁发的";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }else if(indexPath.row==1){
            txtContent =[[UITextView alloc]init];
            txtContent.text = sharePhotoContentPlaceHolder;
            txtContent.contentMode  = UIViewContentModeTopLeft;
            txtContent.textAlignment = NSTextAlignmentLeft;
            txtContent.textColor = [UIColor grayColor];
            txtContent.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
            txtContent.editable = YES;
            txtContent.delegate = self;
            [cell.contentView addSubview:txtContent];
            //输入框
            [txtContent mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(cell.contentView).offset(0);
                make.left.mas_equalTo(cell.contentView).offset(10);
                make.right.mas_equalTo(cell.contentView).offset(0);
                make.height.mas_equalTo(80);
            }];
            
            imageView = [[UIImageView alloc]initWithImage:image];
            [cell.contentView addSubview:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(txtContent).offset(90);
                make.left.mas_equalTo(cell.contentView).offset(10);
                make.width.mas_equalTo(100);
                if(image){
                    make.height.mas_equalTo(image.size.height*100/image.size.width);
                }else{
                    make.height.mas_equalTo(100);
                }
            }];
        }
    }else if (indexPath.section==1) {
        cell.textLabel.text = @"所在位置";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DDLogInfo(@"%ld,%ld",indexPath.section,indexPath.row);
    if(indexPath.section == 1 && indexPath.row == 0){
        ViewController * view = [[ViewController alloc] init];
        view.navigationItem.title = @"选择位置";
        view.chooseAddress = ^(CGFloat lat ,CGFloat lon, NSString* poiName, NSString * address){
            [model setLat:lat];
            [model setLon:lon];
            [model setPoiName:poiName];
            [model setAddress:address];
            UITableViewCell * cell = [table cellForRowAtIndexPath:indexPath];
            if(address){
                cell.textLabel.text = address;
            }
        };
        view.lat = model.lat;
        view.lon = model.lon;
        view.address = model.address;
        view.poiName = model.poiName;
        UIBarButtonItem * right = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"choose"] style:UIBarButtonItemStylePlain target:view action:@selector(chooseAddress:)];
        view.navigationItem.rightBarButtonItem = right;
        [self.navigationController pushViewController:view animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0 && indexPath.row == 1){
        return 250;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0 && indexPath.row == 1){
        return 250;
    }
    return 44;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    if([textView.text compare: sharePhotoContentPlaceHolder] == NSOrderedSame){
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    if([textView.text compare: sharePhotoContentPlaceHolder] == NSOrderedSame){
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }else if([textView.text compare: @""] == NSOrderedSame){
        textView.text = sharePhotoContentPlaceHolder;
        textView.textColor = [UIColor grayColor];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [txtContent resignFirstResponder];
}

@end
